package com.capinfo.accumulation.web.controller.collection;

import com.capinfo.accumulation.model.collection.PersonAccountFund;
import com.capinfo.accumulation.model.collection.PersonHistory;
import com.capinfo.accumulation.parameter.collection.PersonAccountFundParameter;
import com.capinfo.accumulation.parameter.collection.PersonHistoryAccountFundParameter;
import com.capinfo.accumulation.parameter.collection.PersonHistoryParameter;
import com.capinfo.accumulation.service.collection.PersonAccountFundService;
import com.capinfo.accumulation.service.collection.PersonHistoryAccountFundService;
import com.capinfo.accumulation.service.collection.PersonHistoryService;
import com.capinfo.commons.project.service.security.SystemUserService;
import com.capinfo.commons.project.web.controller.manage.region.RegionManageController;
import com.capinfo.framework.model.dictionary.Dictionary;
import com.capinfo.framework.service.CommonsDataOperationService;
import com.capinfo.framework.util.IOUtils;
import com.capinfo.framework.web.controller.CommonsDataManageController;
import com.capinfo.framework.web.util.ControllerUtils;
import com.capinfo.framework.web.util.WebRequestUtils;
import com.capinfo.framework.web.view.model.DataListViewModel;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.servlet.ModelAndView;

import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by wangyulin on 2017/9/27.
 */


@Controller
@RequestMapping("/business/collection/person_account_fund")
public class PersonAccountFundController extends CommonsDataManageController<PersonAccountFundParameter, PersonAccountFund> {

    private static final Log logger = LogFactory.getLog(RegionManageController.class);
    @Autowired
    private PersonAccountFundService personAccountFundService;

    @Autowired
    private SystemUserService systemUserService;

    @Autowired
    private PersonHistoryAccountFundService personHistoryAccountFundService;

    @Autowired
    private PersonHistoryService personHistoryService;

    @Override
    public CommonsDataOperationService<PersonAccountFund, PersonAccountFundParameter> getCommonsDataOperationService() {

        return personAccountFundService;
    }


    @RequestMapping("/form_option.shtml")
    public ModelAndView formOption(NativeWebRequest request,PersonAccountFundParameter parameter){


        ModelAndView mav = new ModelAndView();
        PersonAccountFund objectById = personAccountFundService.getObjectById(parameter);
        if(objectById!=null){
            parameter.setEntity(objectById);
            parameter.setEntityPerson(objectById.getPerson());

            //单位账号
            mav.addObject("companyAccount",parameter.getEntity().getCompanyAccountFund().getCompany().getGbCompanyName());
            //个人账号
            mav.addObject("entityPerson.personalAccount",parameter.getEntityPerson().getPersonalAccount());
            //单位名称
            mav.addObject("companyName",parameter);

        }
        mav.addObject("command",parameter);
        //字典
        Set<Dictionary> regionIdList = personAccountFundService.getDictionariesBySortName("区县");
        mav.addObject("regionIdList",regionIdList);
        Set<Dictionary> legalPersonIdCardTypeIdList = personAccountFundService.getDictionariesBySortName("证件类型");
        mav.addObject("legalPersonIdCardTypeIdList",legalPersonIdCardTypeIdList);
        Set<Dictionary> sexList = personAccountFundService.getDictionariesBySortName("性别");
        mav.addObject("sexList",sexList);
        Set<Dictionary> depositRateMarkIdList = personAccountFundService.getDictionariesBySortName("缴存率标志");
        mav.addObject("depositRateMarkIdList",depositRateMarkIdList);
        //字典end

        String extra = parameter.getExtra();
        Map viewModel = new HashMap<String, Object>();
        if(extra!=null && "extra".equals(extra)){
            mav.setViewName("/business/collection/person_account_fund/supplement_form"); //补充公积金账户开户
        }else {
            mav.setViewName("/business/collection/person_account_fund/form"); //基本公积金账户开户
        }

        //        if(parameter.getDeposit()=="deposit"){   //判断是否为封存专户
//            Company depositCompany = personAccountFundService.getDepositPerson();
//            viewModel.put("depositCompany",depositCompany);
//        }

        return mav;

    }

    @Override
    protected Map<String, Object> formAfterInvoke(NativeWebRequest request, PersonAccountFundParameter parameter, Map<String, Object> viewModel) {
        Set<Dictionary> regionIdList = personAccountFundService.getDictionariesBySortName("区县");
        viewModel.put("regionIdList",regionIdList);
        Set<Dictionary> legalPersonIdCardTypeIdList = personAccountFundService.getDictionariesBySortName("证件类型");
        viewModel.put("legalPersonIdCardTypeIdList",legalPersonIdCardTypeIdList);
        Set<Dictionary> sexList = personAccountFundService.getDictionariesBySortName("性别");
        viewModel.put("sexList",sexList);
        Set<Dictionary> depositRateMarkIdList = personAccountFundService.getDictionariesBySortName("缴存率标志");
        viewModel.put("depositRateMarkIdList",depositRateMarkIdList);
//        if(parameter.getDeposit()=="deposit"){   //判断是否为封存专户
//            Company depositCompany = personAccountFundService.getDepositPerson();
//            viewModel.put("depositCompany",depositCompany);
//        }

        logger.info(parameter.getExtra());
        //判断是否为补充公积金开户
        if("extra".equals(parameter.getExtra())){
            String personAccountFundJson = this.getInfo(request,parameter);
            viewModel.put("personAccountFund",personAccountFundJson);
        }

        return super.formAfterInvoke(request, parameter, viewModel);
    }


    /**获取个人信息
     * 张旭
     * 2017年10月24日19:14:39
     * @param request
     * @param parameter 个人账号 身份证号码
     * @return
     */
//    @RequestMapping("/get_person.shtml")
//    @ResponseBody
//    public String getCompany(NativeWebRequest request, PersonParameter parameter) {
//        JSONObject personJson = new JSONObject();
//            Person getPerson = personService.getPerson(parameter);
//            if (getPerson != null) {
//                personJson.put("result", true);
//                personJson.put("person.id", getPerson.getId());
//                personJson.put("person.name", getPerson.getName());
//                personJson.put("person.sex", getPerson.getSex());
//                personJson.put("person.birthYearMonth", getPerson.getBirthYearMonth());
//                personJson.put("person.idCardTypeId", getPerson.getIdCardTypeId());
//                personJson.put("person.idCardNumber", getPerson.getIdCardNumber());
//                //个人账号
//                personJson.put("person.personalAccount", getPerson.getPersonalAccount());
//                //单位账号
//                personJson.put("person.company.gbCompanyAccount", getPerson.getCompany().getGbCompanyAccount());
//                //单位名称
//                personJson.put("person.company.gbCompanyName", getPerson.getCompany().getGbCompanyName());
//
//
//            }else{
//                personJson.put("result", false);
//            }
//        return personJson.toString();
//
//    }

    /** 显示重复证件号码的账户信息
     * liubin
     * 2017年10月25日21:16:39
     * @param request
     * @return
     */
    @RequestMapping("/account_infomation.shtml")
    public Map<String, Object> accountInfomation(NativeWebRequest request) {

        Map<String, Object> viewModel = new HashMap<String, Object>();

        return viewModel;
    }

    //通过个人账号查询信息
    public String getInfo(NativeWebRequest request, PersonAccountFundParameter parameter) {
        JSONObject personAccountFundJson = new JSONObject();
        PersonAccountFund personAccountFund = personAccountFundService.getPersonAccountFund(parameter);
        if (personAccountFund != null) {
            personAccountFundJson.put("result", true);
            //单位账号
            personAccountFundJson.put("entityPerson.company.gbCompanyAccount", personAccountFund.getPerson().getCompany().getGbCompanyAccount());
            //单位名称
            personAccountFundJson.put("entityPerson.company.gbCompanyName", personAccountFund.getPerson().getCompany().getGbCompanyName());
            //缴存率标志
            personAccountFundJson.put("entity.companyAccountFund.depositRateMarkId", personAccountFund.getPerson().getCompany().getCompanyAccountFunds().get(0).getDepositRateMarkId());
            //单位缴存比例（需要获取补充公积金的缴存比例）
            personAccountFundJson.put("entity.companyAccountFund.companyPaymentRatio", personAccountFund.getPerson().getCompany().getCompanyAccountFunds().get(0).getCompanyPaymentRatio());
            //个人缴存比例（需要获取补充公积金的缴存比例）
            personAccountFundJson.put("entity.companyAccountFund.personPaymentRatio", personAccountFund.getPerson().getCompany().getCompanyAccountFunds().get(0).getPersonPaymentRatio());

            personAccountFundJson.put("entityPerson.idCardTypeId", personAccountFund.getPerson().getIdCardTypeId());
            personAccountFundJson.put("entityPerson.idCardNumber", personAccountFund.getPerson().getIdCardNumber());
            personAccountFundJson.put("entityPerson.name", personAccountFund.getPerson().getName());
            logger.info(personAccountFund.getPerson().getBirthYearMonth());
            if(personAccountFund.getPerson()!=null){
                if(personAccountFund.getPerson().getBirthYearMonth()!=null){
                    String birthDayString = (new SimpleDateFormat("yyyy-MM-dd")).format(personAccountFund.getPerson().getBirthYearMonth());
                    personAccountFundJson.put("entityPerson.birthYearMonth", birthDayString);
                }
            }
            personAccountFundJson.put("entityPerson.sexId", personAccountFund.getPerson().getSexId());
            personAccountFundJson.put("entityPerson.koseki", personAccountFund.getPerson().getKoseki());
            personAccountFundJson.put("entityPerson.wageIncome", personAccountFund.getPerson().getWageIncome());
            personAccountFundJson.put("entity.monthPay", personAccountFund.getMonthPay());
            //个人账号
//            personAccountFundJson.put("entityPerson.personalAccount", personAccountFund.getPerson().getPersonAccountFund());

            logger.info(personAccountFund.getPerson().getHistoryId());
            //最新历史id
            personAccountFundJson.put("entityPerson.id", personAccountFund.getPerson().getHistoryId());

        }else{
            personAccountFundJson.put("result", false);
        }
        return personAccountFundJson.toString();

    }
    @RequestMapping("/person_audit.shtml")
    public void audit(NativeWebRequest request, PersonAccountFundParameter parameter, OutputStream stream) throws UnsupportedEncodingException {
        WebRequestUtils.setCharacterEncodingForUTF8(request);
        WebRequestUtils.setContentTypeForHTML(request);

        PersonAccountFund personAccount = personAccountFundService.audit(parameter);
        if (personAccount!=null) {
            JSONObject json = new JSONObject();
            json.put("id", parameter.getEntity().getId());
            json.put("result", "success");
            json.put("isFirstSave", parameter.getIsFirstSave());
            IOUtils.outputByStream(stream, json.toString().getBytes("UTF-8"));
        } else {

            IOUtils.outputByStream(stream, Boolean.FALSE.toString().getBytes());
        }
    }
    @RequestMapping("/info_change.shtml")
    public Map<String, Object> infoChange(NativeWebRequest request,PersonHistoryAccountFundParameter parameter){

        //不知道是用personHistoryService 还是用personHistoryAccountFundService  ？？？？？
        personHistoryAccountFundService.populateParameter(parameter);

        Map<String, Object> viewModel = ControllerUtils.buildViewModel(parameter);

        viewModel.put("personAccountFundId",parameter.getEntity().getPersonAccountFundId());

//        return formAfterInvoke(request, parameter, viewModel);

        return viewModel;

//        return ControllerUtils.buildViewModel(parameter);
    }

    @RequestMapping("/change_list.shtml")
    public Map<String, Object> changeList(NativeWebRequest request, PersonHistoryAccountFundParameter parameter){
        Map<String, Object> viewModel = ControllerUtils.buildViewModel();

        PersonHistoryParameter personHistoryParameter = new PersonHistoryParameter();
        PersonAccountFundParameter personAccountFundParameter = new PersonAccountFundParameter();
        personHistoryParameter.getEntity().setId(parameter.getEntity().getPersonAccountFundId());
        personAccountFundParameter.getEntity().setId(parameter.getEntity().getPersonAccountFundId());

        PersonAccountFund personAccountFund = personAccountFundService.getObjectById(personAccountFundParameter);


        personHistoryParameter.getEntity().setPersonId(personAccountFund.getPersonId());

        List<PersonHistory> entities = new ArrayList<PersonHistory>();

        long totalCount = personHistoryService.getTotalCount(personHistoryParameter);
        if (0 != totalCount) {

            entities = personHistoryService.getList(personHistoryParameter,totalCount,parameter.getCurrentPieceNum());
        }

        viewModel.putAll(new DataListViewModel<PersonHistory>(personHistoryParameter.getEntityClazz().getSimpleName() + "List", entities, totalCount, personHistoryService, personHistoryParameter).buildViewModel());

        return viewModel;

    }

    @RequestMapping("/change_form.shtml")
    public Map<String, Object> changeForm(NativeWebRequest request,PersonAccountFundParameter parameter){

        Map<String, Object> viewModel = ControllerUtils.buildViewModel(parameter);
        String personAccountFundJson = this.getInfo(request,parameter);
        viewModel.put("personAccountFund",personAccountFundJson);

        return formAfterInvoke(request, parameter, viewModel);
//        return viewModel;
    }

    @RequestMapping("/show_diffence.shtml")
    public Map<String, Object> showDiffence(NativeWebRequest request,PersonHistoryParameter personHistoryParameter) {

        //变更后
        PersonHistory personHistoryAfter = personHistoryService.getObjectById(personHistoryParameter);

        //变更前
        personHistoryParameter.getEntity().setId(personHistoryAfter.getPreviousId());
        personHistoryParameter.setId(personHistoryAfter.getPreviousId());
        PersonHistory personHistory = personHistoryService.getObjectById(personHistoryParameter);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result",true);

        jsonObject.put("nameBefore",personHistory.getName());
        jsonObject.put("nameAfter",personHistoryAfter.getName());

        Map<String, Object> viewModel = new HashMap<String, Object>();

        viewModel.put("personHistoryJson",jsonObject);

        viewModel.put("personHistory",personHistory);
        viewModel.put("personHistoryAfter",personHistoryAfter);


        return viewModel;
    }
}
